using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Security.Cryptography;
using System.Text;
using JGSY.CMS.LowCode.Platform.Application.DTOs.Monitoring;
using JGSY.CMS.LowCode.Platform.Application.Interfaces.Monitoring;
using JGSY.CMS.LowCode.Platform.Domain.Entities.Monitoring;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Application.Services.Monitoring;

/// <summary>
/// 监控服务实现
/// 处理性能指标、错误日志、用户交互的记录和分析
/// </summary>
public class MonitoringService : IMonitoringService
{
    private readonly LowCodeDbContext _context;
    private readonly ILogger<MonitoringService> _logger;

    public MonitoringService(LowCodeDbContext context, ILogger<MonitoringService> logger)
    {
        _context = context;
        _logger = logger;
    }

    /// <summary>
    /// 批量记录性能指标
    /// </summary>
    public async Task<bool> RecordPerformanceMetricsAsync(List<PerformanceMetricDto> metrics)
    {
        try
        {
            var entities = metrics.Select(m => new MonitorPerformanceMetric
            {
                SessionId = m.SessionId,
                UserId = m.UserId,
                MetricName = m.MetricName,
                MetricValue = m.MetricValue,
                MetricRating = m.MetricRating,
                PageUrl = m.PageUrl,
                UserAgent = m.UserAgent,
                BrowserName = m.BrowserName,
                DeviceType = m.DeviceType,
                Timestamp = m.Timestamp,
                CreatedAt = DateTime.UtcNow
            }).ToList();

            await _context.MonitorPerformanceMetrics.AddRangeAsync(entities);
            await _context.SaveChangesAsync();

            // 异步更新会话汇总
            _ = Task.Run(() => UpdateSessionSummaryAsync(metrics.First().SessionId));

            _logger.LogInformation($"Recorded {metrics.Count} performance metrics for session {metrics.First().SessionId}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error recording performance metrics");
            return false;
        }
    }

    /// <summary>
    /// 记录错误日志
    /// </summary>
    public async Task<bool> RecordErrorAsync(ErrorLogDto error)
    {
        try
        {
            var entity = new MonitorErrorLog
            {
                SessionId = error.SessionId,
                UserId = error.UserId,
                ErrorType = error.ErrorType,
                ErrorMessage = error.ErrorMessage,
                ErrorStack = error.ErrorStack,
                ErrorFilename = error.ErrorFilename,
                ErrorLineNumber = error.ErrorLineNumber,
                ErrorColumnNumber = error.ErrorColumnNumber,
                PageUrl = error.PageUrl,
                UserAgent = error.UserAgent,
                Severity = error.Severity,
                Fingerprint = GenerateErrorFingerprint(error),
                Timestamp = error.Timestamp,
                CreatedAt = DateTime.UtcNow
            };

            await _context.MonitorErrorLogs.AddAsync(entity);
            await _context.SaveChangesAsync();

            // 异步更新会话错误计数
            _ = Task.Run(() => UpdateSessionErrorCountAsync(error.SessionId));

            _logger.LogWarning($"Recorded error: {error.ErrorType} - {error.ErrorMessage}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error recording error log");
            return false;
        }
    }

    /// <summary>
    /// 记录用户交互
    /// </summary>
    public async Task<bool> RecordUserInteractionAsync(UserInteractionDto interaction)
    {
        try
        {
            var entity = new MonitorUserInteraction
            {
                SessionId = interaction.SessionId,
                InteractionType = interaction.InteractionType,
                PageUrl = interaction.PageUrl,
                TargetElement = interaction.TargetElement,
                ElementText = interaction.ElementText,
                RouteFrom = interaction.RouteFrom,
                RouteTo = interaction.RouteTo,
                ScrollDepth = interaction.ScrollDepth,
                FormData = interaction.FormData,
                Duration = interaction.Duration,
                Timestamp = interaction.Timestamp,
                CreatedAt = DateTime.UtcNow
            };

            await _context.MonitorUserInteractions.AddAsync(entity);
            await _context.SaveChangesAsync();

            _logger.LogDebug($"Recorded user interaction: {interaction.InteractionType} on {interaction.PageUrl}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error recording user interaction");
            return false;
        }
    }

    /// <summary>
    /// 获取监控仪表板数据
    /// </summary>
    public async Task<MonitoringDashboardDto> GetDashboardDataAsync(DateTime? startDate = null, DateTime? endDate = null)
    {
        try
        {
            var end = endDate ?? DateTime.UtcNow;
            var start = startDate ?? end.AddHours(-24);
            var startTimestamp = ((DateTimeOffset)start).ToUnixTimeMilliseconds();
            var endTimestamp = ((DateTimeOffset)end).ToUnixTimeMilliseconds();

            var dashboard = new MonitoringDashboardDto();

            // 获取摘要信息
            dashboard.Summary = await GetDashboardSummaryAsync(startTimestamp, endTimestamp);

            // 获取性能趋势
            dashboard.PerformanceTrends = await GetPerformanceTrendsInternalAsync(startTimestamp, endTimestamp);

            // 获取错误统计
            dashboard.ErrorStatistics = await GetErrorStatisticsAsync(startTimestamp, endTimestamp);

            // 获取会话分析
            dashboard.SessionAnalysis = await GetSessionAnalysisAsync(startTimestamp, endTimestamp);

            return dashboard;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting dashboard data");
            return new MonitoringDashboardDto();
        }
    }

    /// <summary>
    /// 获取错误汇总信息
    /// </summary>
    public async Task<List<RecentErrorDto>> GetErrorSummaryAsync(int limit = 50)
    {
        try
        {
            var recentErrors = await _context.MonitorErrorLogs
                .Where(e => e.CreatedAt >= DateTime.UtcNow.AddHours(-24))
                .GroupBy(e => new { e.ErrorType, e.ErrorMessage, e.PageUrl })
                .Select(g => new RecentErrorDto
                {
                    Id = g.First().Id,
                    ErrorType = g.Key.ErrorType,
                    ErrorMessage = g.Key.ErrorMessage,
                    PageUrl = g.Key.PageUrl,
                    Severity = g.First().Severity,
                    Count = g.Count(),
                    LastOccurred = g.Max(e => e.CreatedAt)
                })
                .OrderByDescending(e => e.LastOccurred)
                .Take(limit)
                .ToListAsync();

            return recentErrors;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting error summary");
            return new List<RecentErrorDto>();
        }
    }

    /// <summary>
    /// 获取会话详情
    /// </summary>
    public async Task<SessionDetailDto> GetSessionDetailAsync(string sessionId)
    {
        try
        {
            var session = await _context.MonitorSessionSummary
                .FirstOrDefaultAsync(s => s.SessionId == sessionId);

            if (session == null)
                return new SessionDetailDto(); // 返回空的详情对象而不是 null

            var metrics = await _context.MonitorPerformanceMetrics
                .Where(m => m.SessionId == sessionId)
                .GroupBy(m => m.MetricName)
                .Select(g => new { MetricName = g.Key, AvgValue = g.Average(m => m.MetricValue) })
                .ToDictionaryAsync(x => x.MetricName, x => x.AvgValue);

            var errors = await _context.MonitorErrorLogs
                .Where(e => e.SessionId == sessionId)
                .Select(e => new SessionErrorDto
                {
                    Id = e.Id,
                    ErrorType = e.ErrorType,
                    ErrorMessage = e.ErrorMessage,
                    PageUrl = e.PageUrl,
                    Severity = e.Severity,
                    OccurredAt = e.CreatedAt
                })
                .ToListAsync();

            var visitedPages = await _context.MonitorPerformanceMetrics
                .Where(m => m.SessionId == sessionId)
                .Select(m => m.PageUrl)
                .Distinct()
                .ToListAsync();

            return new SessionDetailDto
            {
                SessionId = session.SessionId,
                UserId = session.UserId,
                SessionStart = DateTimeOffset.FromUnixTimeMilliseconds(session.SessionStart).DateTime,
                SessionEnd = session.SessionEnd.HasValue 
                    ? DateTimeOffset.FromUnixTimeMilliseconds(session.SessionEnd.Value).DateTime 
                    : null,
                SessionDuration = session.SessionDuration,
                PageViews = session.PageViews,
                ErrorCount = session.ErrorCount,
                PerformanceMetrics = metrics,
                BrowserName = session.BrowserName,
                DeviceType = session.DeviceType,
                VisitedPages = visitedPages,
                Errors = errors
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error getting session detail for {sessionId}");
            return new SessionDetailDto(); // 返回空的详情对象而不是 null
        }
    }

    /// <summary>
    /// 清理过期数据
    /// </summary>
    public async Task<int> CleanupExpiredDataAsync(int retentionDays = 90)
    {
        try
        {
            var cutoffDate = DateTime.UtcNow.AddDays(-retentionDays);
            var cutoffTimestamp = ((DateTimeOffset)cutoffDate).ToUnixTimeMilliseconds();

            // 清理性能指标
            var expiredMetrics = _context.MonitorPerformanceMetrics
                .Where(m => m.Timestamp < cutoffTimestamp);
            var metricsCount = await expiredMetrics.CountAsync();
            _context.MonitorPerformanceMetrics.RemoveRange(expiredMetrics);

            // 清理错误日志
            var expiredErrors = _context.MonitorErrorLogs
                .Where(e => e.Timestamp < cutoffTimestamp);
            var errorsCount = await expiredErrors.CountAsync();
            _context.MonitorErrorLogs.RemoveRange(expiredErrors);

            // 清理用户交互
            var expiredInteractions = _context.MonitorUserInteractions
                .Where(i => i.Timestamp < cutoffTimestamp);
            var interactionsCount = await expiredInteractions.CountAsync();
            _context.MonitorUserInteractions.RemoveRange(expiredInteractions);

            // 清理会话汇总
            var expiredSessions = _context.MonitorSessionSummary
                .Where(s => s.SessionStart < cutoffTimestamp);
            var sessionsCount = await expiredSessions.CountAsync();
            _context.MonitorSessionSummary.RemoveRange(expiredSessions);

            await _context.SaveChangesAsync();

            var totalCleaned = metricsCount + errorsCount + interactionsCount + sessionsCount;
            _logger.LogInformation($"Cleaned up {totalCleaned} expired monitoring records older than {retentionDays} days");

            return totalCleaned;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error cleaning up expired data");
            return 0;
        }
    }

    /// <summary>
    /// 获取性能趋势数据
    /// </summary>
    public async Task<List<PerformanceTrendDto>> GetPerformanceTrendsAsync(string metricName, int hours = 24)
    {
        try
        {
            var startTime = ((DateTimeOffset)DateTime.UtcNow.AddHours(-hours)).ToUnixTimeMilliseconds();

            var trends = await _context.MonitorPerformanceMetrics
                .Where(m => m.MetricName == metricName && m.Timestamp >= startTime)
                .GroupBy(m => new { 
                    Hour = (m.Timestamp - startTime) / (60 * 60 * 1000) // 小时分组
                })
                .Select(g => new PerformanceTrendDto
                {
                    Time = DateTime.UtcNow.AddHours(-hours + g.Key.Hour),
                    LCP = metricName == "LCP" ? g.Average(m => m.MetricValue) : 0,
                    FID = metricName == "FID" ? g.Average(m => m.MetricValue) : 0,
                    CLS = metricName == "CLS" ? g.Average(m => m.MetricValue) : 0,
                    SampleCount = g.Count()
                })
                .OrderBy(t => t.Time)
                .ToListAsync();

            return trends;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error getting performance trends for {metricName}");
            return new List<PerformanceTrendDto>();
        }
    }

    #region 私有辅助方法

    /// <summary>
    /// 生成错误指纹用于去重
    /// </summary>
    private string GenerateErrorFingerprint(ErrorLogDto error)
    {
        var content = $"{error.ErrorType}_{error.ErrorMessage}_{error.ErrorFilename}_{error.ErrorLineNumber}";
        using var sha256 = SHA256.Create();
        var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(content));
        return Convert.ToHexString(hash)[..16]; // 取前16位作为指纹
    }

    /// <summary>
    /// 更新会话汇总信息
    /// </summary>
    private async Task UpdateSessionSummaryAsync(string sessionId)
    {
        try
        {
            var metrics = await _context.MonitorPerformanceMetrics
                .Where(m => m.SessionId == sessionId)
                .ToListAsync();

            if (!metrics.Any()) return;

            var session = await _context.MonitorSessionSummary
                .FirstOrDefaultAsync(s => s.SessionId == sessionId);

            if (session == null)
            {
                // 创建新的会话汇总
                session = new MonitorSessionSummary
                {
                    SessionId = sessionId,
                    UserId = metrics.First().UserId,
                    SessionStart = metrics.Min(m => m.Timestamp),
                    BrowserName = metrics.First().BrowserName,
                    DeviceType = metrics.First().DeviceType,
                    CreatedAt = DateTime.UtcNow
                };
                _context.MonitorSessionSummary.Add(session);
            }

            // 更新性能指标平均值
            var lcpMetrics = metrics.Where(m => m.MetricName == "LCP").ToList();
            if (lcpMetrics.Any())
                session.AvgLCP = lcpMetrics.Average(m => m.MetricValue);

            var fidMetrics = metrics.Where(m => m.MetricName == "FID").ToList();
            if (fidMetrics.Any())
                session.AvgFID = fidMetrics.Average(m => m.MetricValue);

            var clsMetrics = metrics.Where(m => m.MetricName == "CLS").ToList();
            if (clsMetrics.Any())
                session.AvgCLS = clsMetrics.Average(m => m.MetricValue);

            var fcpMetrics = metrics.Where(m => m.MetricName == "FCP").ToList();
            if (fcpMetrics.Any())
                session.AvgFCP = fcpMetrics.Average(m => m.MetricValue);

            var ttfbMetrics = metrics.Where(m => m.MetricName == "TTFB").ToList();
            if (ttfbMetrics.Any())
                session.AvgTTFB = ttfbMetrics.Average(m => m.MetricValue);

            // 更新页面浏览数
            session.PageViews = metrics.Select(m => m.PageUrl).Distinct().Count();
            session.SessionEnd = metrics.Max(m => m.Timestamp);
            session.SessionDuration = (int)((session.SessionEnd.Value - session.SessionStart) / 1000 / 60); // 分钟
            session.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error updating session summary for {sessionId}");
        }
    }

    /// <summary>
    /// 更新会话错误计数
    /// </summary>
    private async Task UpdateSessionErrorCountAsync(string sessionId)
    {
        try
        {
            var session = await _context.MonitorSessionSummary
                .FirstOrDefaultAsync(s => s.SessionId == sessionId);

            if (session != null)
            {
                session.ErrorCount = await _context.MonitorErrorLogs
                    .CountAsync(e => e.SessionId == sessionId);
                session.UpdatedAt = DateTime.UtcNow;

                await _context.SaveChangesAsync();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error updating session error count for {sessionId}");
        }
    }

    /// <summary>
    /// 获取仪表板摘要信息
    /// </summary>
    private async Task<DashboardSummaryDto> GetDashboardSummaryAsync(long startTimestamp, long endTimestamp)
    {
        var summary = new DashboardSummaryDto();

        // 活跃会话数
        summary.ActiveSessions = await _context.MonitorSessionSummary
            .CountAsync(s => s.SessionStart >= startTimestamp && 
                           (s.SessionEnd == null || s.SessionEnd >= startTimestamp));

        // 错误总数
        summary.TotalErrors = await _context.MonitorErrorLogs
            .CountAsync(e => e.Timestamp >= startTimestamp && e.Timestamp <= endTimestamp);

        // Core Web Vitals 平均值
        var metrics = await _context.MonitorPerformanceMetrics
            .Where(m => m.Timestamp >= startTimestamp && m.Timestamp <= endTimestamp)
            .GroupBy(m => m.MetricName)
            .Select(g => new { MetricName = g.Key, AvgValue = g.Average(m => m.MetricValue) })
            .ToListAsync();

        summary.AvgLCP = metrics.FirstOrDefault(m => m.MetricName == "LCP")?.AvgValue ?? 0;
        summary.AvgFID = metrics.FirstOrDefault(m => m.MetricName == "FID")?.AvgValue ?? 0;
        summary.AvgCLS = metrics.FirstOrDefault(m => m.MetricName == "CLS")?.AvgValue ?? 0;
        summary.AvgFCP = metrics.FirstOrDefault(m => m.MetricName == "FCP")?.AvgValue ?? 0;
        summary.AvgTTFB = metrics.FirstOrDefault(m => m.MetricName == "TTFB")?.AvgValue ?? 0;

        return summary;
    }

    /// <summary>
    /// 获取性能趋势数据（内部方法）
    /// </summary>
    private async Task<List<PerformanceTrendDto>> GetPerformanceTrendsInternalAsync(long startTimestamp, long endTimestamp)
    {
        var hourlyTrends = await _context.MonitorPerformanceMetrics
            .Where(m => m.Timestamp >= startTimestamp && m.Timestamp <= endTimestamp)
            .GroupBy(m => new { 
                Hour = (m.Timestamp - startTimestamp) / (60 * 60 * 1000),
                MetricName = m.MetricName
            })
            .Select(g => new { 
                Hour = g.Key.Hour, 
                MetricName = g.Key.MetricName, 
                AvgValue = g.Average(m => m.MetricValue),
                Count = g.Count()
            })
            .ToListAsync();

        var trends = hourlyTrends
            .GroupBy(h => h.Hour)
            .Select(g => new PerformanceTrendDto
            {
                Time = DateTimeOffset.FromUnixTimeMilliseconds(startTimestamp).AddHours(g.Key).DateTime,
                LCP = g.FirstOrDefault(x => x.MetricName == "LCP")?.AvgValue ?? 0,
                FID = g.FirstOrDefault(x => x.MetricName == "FID")?.AvgValue ?? 0,
                CLS = g.FirstOrDefault(x => x.MetricName == "CLS")?.AvgValue ?? 0,
                SampleCount = g.Sum(x => x.Count)
            })
            .OrderBy(t => t.Time)
            .ToList();

        return trends;
    }

    /// <summary>
    /// 获取错误统计数据
    /// </summary>
    private async Task<ErrorStatisticsDto> GetErrorStatisticsAsync(long startTimestamp, long endTimestamp)
    {
        var statistics = new ErrorStatisticsDto();

        // 按类型分组
        statistics.ByType = await _context.MonitorErrorLogs
            .Where(e => e.Timestamp >= startTimestamp && e.Timestamp <= endTimestamp)
            .GroupBy(e => e.ErrorType)
            .ToDictionaryAsync(g => g.Key, g => g.Count());

        // 按严重程度分组
        statistics.BySeverity = await _context.MonitorErrorLogs
            .Where(e => e.Timestamp >= startTimestamp && e.Timestamp <= endTimestamp)
            .GroupBy(e => e.Severity)
            .ToDictionaryAsync(g => g.Key, g => g.Count());

        // 最近错误
        statistics.RecentErrors = await GetErrorSummaryAsync(10);

        return statistics;
    }

    /// <summary>
    /// 获取会话分析数据
    /// </summary>
    private async Task<SessionAnalysisDto> GetSessionAnalysisAsync(long startTimestamp, long endTimestamp)
    {
        var analysis = new SessionAnalysisDto();

        var sessions = await _context.MonitorSessionSummary
            .Where(s => s.SessionStart >= startTimestamp)
            .ToListAsync();

        analysis.TodaySessions = sessions.Count;
        analysis.AvgSessionDuration = sessions.Where(s => s.SessionDuration.HasValue)
                                            .Select(s => (decimal)s.SessionDuration!.Value)
                                            .DefaultIfEmpty(0)
                                            .Average();

        // 跳出率（只访问一个页面的会话比例）
        var bounceCount = sessions.Count(s => s.PageViews <= 1);
        analysis.BounceRate = sessions.Any() ? (decimal)bounceCount / sessions.Count * 100 : 0;

        // 设备类型分布
        analysis.DeviceDistribution = sessions
            .Where(s => !string.IsNullOrEmpty(s.DeviceType))
            .GroupBy(s => s.DeviceType)
            .ToDictionary(g => g.Key!, g => g.Count());

        // 浏览器分布
        analysis.BrowserDistribution = sessions
            .Where(s => !string.IsNullOrEmpty(s.BrowserName))
            .GroupBy(s => s.BrowserName)
            .ToDictionary(g => g.Key!, g => g.Count());

        return analysis;
    }

    /// <summary>
    /// 解析时间范围
    /// </summary>
    private (DateTime startTime, DateTime endTime) GetTimeRange(string timeRange)
    {
        var endTime = DateTime.UtcNow;
        var startTime = timeRange switch
        {
            "1h" => endTime.AddHours(-1),
            "6h" => endTime.AddHours(-6),
            "24h" => endTime.AddHours(-24),
            "7d" => endTime.AddDays(-7),
            "30d" => endTime.AddDays(-30),
            _ => endTime.AddHours(-24) // 默认24小时
        };
        
        return (startTime, endTime);
    }

    /// <summary>
    /// 大批量数据处理
    /// </summary>
    public async Task<bool> ProcessBulkDataAsync(BulkDataDto bulkData)
    {
        try
        {
            _logger.LogInformation($"Processing bulk data: {bulkData.OperationType}, Items: {bulkData.DataItems.Count}");

            using var transaction = await _context.Database.BeginTransactionAsync();
            
            try
            {
                var batchSize = bulkData.BatchSize;
                var processed = 0;

                for (int i = 0; i < bulkData.DataItems.Count; i += batchSize)
                {
                    var batch = bulkData.DataItems.Skip(i).Take(batchSize);
                    
                    foreach (var item in batch)
                    {
                        // 这里可以根据数据类型进行不同的处理
                        // 暂时只记录日志，实际实现需要根据具体的数据结构来处理
                        _logger.LogDebug($"Processing bulk item: {System.Text.Json.JsonSerializer.Serialize(item)}");
                        processed++;
                    }
                }

                await _context.SaveChangesAsync();
                await transaction.CommitAsync();
                
                _logger.LogInformation($"Successfully processed {processed} items in bulk operation: {bulkData.OperationType}");
                return true;
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                _logger.LogError(ex, $"Failed to process bulk data: {bulkData.OperationType}");
                throw;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in ProcessBulkDataAsync");
            return false;
        }
    }

    /// <summary>
    /// 获取页面分析数据
    /// </summary>
    public async Task<List<PageAnalysisDto>> GetPageAnalysisAsync(string timeRange = "24h", string? page = null)
    {
        try
        {
            var (startTime, endTime) = GetTimeRange(timeRange);
            var startTimestamp = ((DateTimeOffset)startTime).ToUnixTimeMilliseconds();
            var endTimestamp = ((DateTimeOffset)endTime).ToUnixTimeMilliseconds();

            var query = _context.MonitorPerformanceMetrics
                .Where(m => m.Timestamp >= startTimestamp && m.Timestamp <= endTimestamp);

            if (!string.IsNullOrEmpty(page))
            {
                query = query.Where(m => m.PageUrl.Contains(page));
            }

            var pageGroups = await query
                .GroupBy(m => m.PageUrl)
                .Select(g => new PageAnalysisDto
                {
                    PageUrl = g.Key,
                    PageTitle = g.Key, // 可以从其他源获取真实的页面标题
                    ViewCount = g.Count(),
                    UniqueVisitors = g.Select(m => m.SessionId).Distinct().Count(),
                    AverageLoadTime = g.Where(m => m.MetricName == "LCP" || m.MetricName == "FCP")
                                      .Select(m => m.MetricValue)
                                      .DefaultIfEmpty(0)
                                      .Average(),
                    BounceRate = 0, // 需要基于会话数据计算
                    AverageSessionDuration = 0, // 需要基于会话数据计算
                })
                .OrderByDescending(p => p.ViewCount)
                .Take(50)
                .ToListAsync();

            return pageGroups;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetPageAnalysisAsync");
            return new List<PageAnalysisDto>();
        }
    }

    /// <summary>
    /// 获取用户行为分析数据
    /// </summary>
    public async Task<List<UserAnalysisDto>> GetUserAnalysisAsync(string? userId = null, string timeRange = "24h")
    {
        try
        {
            var (startTime, endTime) = GetTimeRange(timeRange);
            var startTimestamp = ((DateTimeOffset)startTime).ToUnixTimeMilliseconds();
            var endTimestamp = ((DateTimeOffset)endTime).ToUnixTimeMilliseconds();

            var sessionsQuery = _context.MonitorSessionSummary
                .Where(s => s.SessionStart >= startTimestamp && s.SessionStart <= endTimestamp);

            if (!string.IsNullOrEmpty(userId))
            {
                sessionsQuery = sessionsQuery.Where(s => s.UserId == userId);
            }

            var userGroups = await sessionsQuery
                .GroupBy(s => s.UserId ?? "anonymous")
                .Select(g => new UserAnalysisDto
                {
                    UserId = g.Key == "anonymous" ? null : g.Key,
                    TotalSessions = g.Count(),
                    TotalPageViews = g.Sum(s => s.PageViews),
                    AverageSessionDuration = g.Where(s => s.SessionDuration.HasValue)
                                             .Select(s => (decimal)s.SessionDuration!.Value)
                                             .DefaultIfEmpty(0)
                                             .Average(),
                    FirstVisit = g.Min(s => DateTimeOffset.FromUnixTimeMilliseconds(s.SessionStart).DateTime),
                    LastVisit = g.Max(s => DateTimeOffset.FromUnixTimeMilliseconds(s.SessionEnd ?? s.SessionStart).DateTime)
                })
                .OrderByDescending(u => u.TotalSessions)
                .Take(100)
                .ToListAsync();

            return userGroups;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetUserAnalysisAsync");
            return new List<UserAnalysisDto>();
        }
    }

    /// <summary>
    /// 获取实时监控数据
    /// </summary>
    public async Task<RealtimeDataDto> GetRealtimeDataAsync()
    {
        try
        {
            var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var fiveMinutesAgo = now - (5 * 60 * 1000); // 5分钟前

            // 活跃会话数（最近5分钟有活动的会话）
            var activeSessions = await _context.MonitorSessionSummary
                .Where(s => (s.SessionEnd ?? s.SessionStart) >= fiveMinutesAgo)
                .CountAsync();

            // 当前页面浏览数
            var currentPageViews = await _context.MonitorPerformanceMetrics
                .Where(m => m.Timestamp >= fiveMinutesAgo)
                .CountAsync();

            // 最近错误
            var recentErrors = await _context.MonitorErrorLogs
                .Where(e => e.Timestamp >= fiveMinutesAgo)
                .OrderByDescending(e => e.Timestamp)
                .Take(10)
                .Select(e => new RecentError
                {
                    ErrorType = e.ErrorType,
                    Message = e.ErrorMessage ?? "Unknown error",
                    PageUrl = e.PageUrl,
                    Severity = e.Severity ?? "medium",
                    Timestamp = e.Timestamp
                })
                .ToListAsync();

            // 活跃页面
            var activePages = await _context.MonitorPerformanceMetrics
                .Where(m => m.Timestamp >= fiveMinutesAgo)
                .GroupBy(m => m.PageUrl)
                .Select(g => new ActivePage
                {
                    Url = g.Key,
                    Title = g.Key,
                    ActiveUsers = g.Select(m => m.SessionId).Distinct().Count(),
                    AverageLoadTime = g.Where(m => m.MetricName == "LCP")
                                      .Select(m => m.MetricValue)
                                      .DefaultIfEmpty(0)
                                      .Average()
                })
                .OrderByDescending(p => p.ActiveUsers)
                .Take(10)
                .ToListAsync();

            var realtimeData = new RealtimeDataDto
            {
                ActiveSessions = activeSessions,
                CurrentPageViews = currentPageViews,
                LiveMetrics = new List<LiveMetric>
                {
                    new() { Name = "Active Sessions", Value = activeSessions, Unit = "count", Trend = "stable", Timestamp = now },
                    new() { Name = "Page Views", Value = currentPageViews, Unit = "count", Trend = "stable", Timestamp = now }
                },
                RecentErrors = recentErrors,
                ActivePages = activePages,
                SystemStatus = new SystemStatus
                {
                    Status = "healthy",
                    CpuUsage = 0, // 需要从系统获取实际值
                    MemoryUsage = 0, // 需要从系统获取实际值
                    DatabaseConnections = _context.Database.CanConnect() ? 1 : 0
                },
                Timestamp = now
            };

            return realtimeData;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetRealtimeDataAsync");
            return new RealtimeDataDto
            {
                ActiveSessions = 0,
                CurrentPageViews = 0,
                SystemStatus = new SystemStatus { Status = "error" },
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            };
        }
    }

    /// <summary>
    /// 获取监控配置
    /// </summary>
    public async Task<MonitoringConfigDto> GetMonitoringConfigAsync()
    {
        try
        {
            // 这里应该从配置存储中获取，现在返回默认配置
            await Task.Delay(1); // 模拟异步操作

            return new MonitoringConfigDto
            {
                Enabled = true,
                SamplingRate = 0.1m,
                BatchSize = 10,
                MaxErrorsPerMinute = 100,
                DataRetentionDays = 90,
                EnableRealTimeNotifications = true,
                PerformanceThresholds = new Dictionary<string, decimal>
                {
                    { "LCP", 4000 },
                    { "FID", 300 },
                    { "CLS", 0.25m },
                    { "FCP", 2500 },
                    { "TTFB", 1500 }
                },
                ErrorFilters = new List<string>
                {
                    "Script error",
                    "Network request failed",
                    "ResizeObserver loop limit exceeded"
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetMonitoringConfigAsync");
            return new MonitoringConfigDto();
        }
    }

    /// <summary>
    /// 更新监控配置
    /// </summary>
    public async Task<bool> UpdateMonitoringConfigAsync(MonitoringConfigDto config)
    {
        try
        {
            // 这里应该将配置保存到配置存储中，现在只记录日志
            _logger.LogInformation($"Updating monitoring config: Enabled={config.Enabled}, SamplingRate={config.SamplingRate}");
            
            await Task.Delay(1); // 模拟异步操作
            
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in UpdateMonitoringConfigAsync");
            return false;
        }
    }

    /// <summary>
    /// 获取系统状态
    /// </summary>
    public async Task<SystemStatus> GetSystemStatusAsync()
    {
        try
        {
            var status = new SystemStatus
            {
                Status = "healthy",
                CpuUsage = 0, // 需要从系统监控获取
                MemoryUsage = 0, // 需要从系统监控获取
                DatabaseConnections = await _context.Database.CanConnectAsync() ? 1 : 0,
                Services = new List<ServiceHealth>
                {
                    new()
                    {
                        ServiceName = "Database",
                        Status = await _context.Database.CanConnectAsync() ? "healthy" : "unhealthy",
                        ResponseTime = 50, // 模拟响应时间
                        LastError = null
                    },
                    new()
                    {
                        ServiceName = "Monitoring",
                        Status = "healthy",
                        ResponseTime = 10,
                        LastError = null
                    }
                }
            };

            return status;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetSystemStatusAsync");
            return new SystemStatus
            {
                Status = "error",
                Services = new List<ServiceHealth>
                {
                    new()
                    {
                        ServiceName = "Monitoring",
                        Status = "error",
                        LastError = ex.Message
                    }
                }
            };
        }
    }

    #endregion
}
